﻿using Qiniu.Http;

using Qiniu.Storage;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace YSL.Application.Services.Qiniu
{
    public class QiniuService
    {
        private readonly string _accessKey;
        private readonly string _secretKey;
        private readonly string _bucket;
        private readonly string _domain;

        public QiniuService(string accessKey, string secretKey, string bucket, string domain)
        {
            _accessKey = accessKey;
            _secretKey = secretKey;
            _bucket = bucket;
            _domain = domain;
        }

        public string Upload(Stream fileStream, string fileName)
        {
            // 1. 生成上传凭证
            Mac mac = new Mac(_accessKey, _secretKey);
            PutPolicy putPolicy = new PutPolicy { Scope = _bucket };
            putPolicy.SetExpires(3600); // 凭证有效期1小时
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

            // 2. 配置上传区域（根据Bucket所在区域选择）
            Config config = new Config { Zone = Zone.ZONE_CN_East }; // 华东区

            // 3. 执行上传（添加PutExtra参数）
            PutExtra putExtra = new PutExtra();
            // 这里可以根据需求设置putExtra的属性，例如：
            // putExtra.Params = new Dictionary<string, string> { { "x:my_custom_param", "value" } };
            // putExtra.MimeType = "image/jpeg";
            // putExtra.Crc32 = CalculateCrc32(fileStream); // 如果需要计算CRC32（可参考七牛云文档实现计算逻辑）

            FormUploader uploader = new FormUploader(config);
            HttpResult result = uploader.UploadStream(fileStream, fileName, token, putExtra);

            // 4. 返回访问URL
            if (result.Code == 200)
                return $"{_domain}/{fileName}";
            else
                throw new Exception($"上传失败：{result.Text}");
        }
    }
}
